package com.bankcomm.ui.views;

import java.util.ArrayList;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bankcomm.R;
import com.bankcomm.common.ConfigManager;
import com.bankcomm.common.LPMid;
import com.bankcomm.location.BaiduLocation;
import com.bankcomm.ui.BCMNewsCenter;
import com.bankcomm.ui.BOCMainHome;
import com.bankcomm.ui.BaseViewCopy;
import com.bankcomm.ui.views.AutoScrollListener.AutoLoadCallBack;
import com.bankcomm.ui.views.PageScrollView.PageListener;
import com.bankcomm.util.LPUtils;
import com.rytong.tools.crypto.AESCipher;
import com.rytong.tools.datastorage.PackageManagerAndroid;
import com.rytong.tools.httpconnect.WaitDialog;
import com.rytong.tools.utils.LPToastUtil;
import com.rytong.tools.utils.Utils;

/**
 * BCMHomeView.java 新版交行首页
 * 
 * @author cheng.l 2013-5-29 下午01:09:20
 */
public class BCMHomeView extends LinearLayout implements OnClickListener{
	/**
	 * 九宫格数组
	 * */
	public DropDragGrid[] mDropGrids = {};
	/**
	 * 九宫格横向滚动视图
	 * */
	public static PageScrollView mScrollView;
	
	/**
	 * 垂直slidingmenu
	 */
	private VerticalSlidingMenu verticalMenu;
	
	/**
	 * 频道标题Tab
	 * */
	private static LinearLayout mPageTab;
	public static LinearLayout mPageTabBottom;
	/**
	 * 首页数据类
	 * */
	public DataStorage mData;
	/**
	 * 标题栏左、右侧按钮,底部左、右侧按钮
	 * */
	public static RelativeLayout bottomRLayout;
	private ImageView /*bottomLeft,*/ bottomRight;
	private Button titleLeft,titleRight;
	/**
	 * 标题view，管理我的首页标题和正常
	 * */
	private static View titleNormal;
	private static View titleManage;
	/**
	 * 编辑状态的取消按钮和完成按钮
	 * */
	private Button cancelButton,confirmButton;
	
	/**
	 * 城市选择按钮
	 * */
	private static TextView mCityView;
	private static ImageView mCityImage;
	/**
	 * 城市列表控件\学校控件
	 * */
	public static LPCitySelectView mSelectCity;
	
	/**
	 * 上部控件，包含广告和天气预报
	 * */
	public LPTopView mTopView;
	private BOCMainHome bv;
	
	/**
	 * 打开关闭广告栏
	 */
	public static ImageView ivOpenClose = null;
	public static boolean isOpen = true;
	/**
	 * 记录当前我的首页
	 */
	public ArrayList<Map<String, Object>> tempList = null;
	private DropGridAdapter favAdapter = null;
	private LPManageHome manageHome = null;
	/**
	 * 记录上一次切换的tab
	 * */
	private static int lastTab = 0;
	private LPMid mid;
	
	private BaiduLocation locationServices;
	
	/*
	 * 消息盒子未读信息数目
	 */
	//private TextView titleLeftnews;
	//String unreadnewscout = "" ;
	//private boolean firstHitNewB = true;
	
	private static Animation topToBottom;
	private static Animation bottomToTop;
	public BCMHomeView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		bv = (BOCMainHome)context;
		init();
	}

	public BCMHomeView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		bv = (BOCMainHome)context;
		init();
	}

	private void init(){
		mid = LPMid.getInstance();
		mData  = mid.um_.data;
		topToBottom = AnimationUtils.loadAnimation(bv, R.anim.in_from_top);
		bottomToTop = AnimationUtils.loadAnimation(bv, R.anim.out_to_bottom);
		
		initView();
		createView();
		setClickListener();
		
		locationServices = BaiduLocation.getInstance();
	}
	
	/**
	 * 刷新view拿到数据后
	 */
	public void refreshViewWithData(){
		mData = mid.um_.data;
		createView();
		mTopView.refresh();
	}
	
	/**
	 * 设置点击事件
	 * */
	private void setClickListener() {
		// TODO Auto-generated method stub
		cancelButton.setOnClickListener(this);
		confirmButton.setOnClickListener(this);
		
		titleLeft.setOnClickListener(this);
		titleRight.setOnClickListener(this);
		//bottomLeft.setOnClickListener(this);
		bottomRight.setOnClickListener(this);
		mCityView.setOnClickListener(this);
		((ImageView)findViewById(R.id.imageSelect)).setOnClickListener(this);
		mScrollView.setPageListener(new PageListener() {
			@Override
			public void page(int page) {
				// TODO Auto-generated method stub
				changeTab(page);
			}
		});

	}
	
	/**
	 * 得到TabView的高度
	 * */
	public static int getTabHeight(){
		return mPageTab.getMeasuredHeight();
	}
	
	/**
	 * 设置PageScrollView是否滚动 
	 * */
	public static void setScroll(boolean isScroll){
		mScrollView.setEnableScroll(isScroll);
	}
	
	/**
	 * 更改选项Tab
	 * */
	public static void changeTab(int position) {
		LPMid.getInstance().currentTab = position;
		if(mPageTab.getChildCount() > 0){
			if (lastTab != position) {
				mPageTab.getChildAt(lastTab).setEnabled(true);
				mPageTab.getChildAt(position).setEnabled(false);
				mPageTabBottom.getChildAt(lastTab).setEnabled(true);
				mPageTabBottom.getChildAt(position).setEnabled(false);
			} else {
				mPageTab.getChildAt(position).setEnabled(false);
				mPageTabBottom.getChildAt(position).setEnabled(false);
			}
			lastTab = position;			
		}
	}

	/**
	 * 更改PageScrollView 和 Tab
	 * */
	public static void changeScrollTab(int index){
		if(index >=0 && index < mScrollView.getChildCount()){
			mScrollView.snapToScreen(index);
			changeTab(mScrollView.getCurScreen());
		}
	}
	
	/**
	 * 实例化各个view对象
	 * */
	private void initView() {
		// TODO Auto-generated method stub
		View root = LayoutInflater.from(bv).inflate(R.layout.layout_home_view, null);
		
		verticalMenu = (VerticalSlidingMenu)root.findViewById(R.id.verticalSlidingView);
		
		//包含天气预报和频道tab
		View center = LayoutInflater.from(bv).inflate(R.layout.layout_home_center_view, null);
		mTopView =  (LPTopView)center.findViewById(R.id.topView);
		mPageTab = (LinearLayout)center.findViewById(R.id.pagetab);
		//设置中间TAB的高度
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,Utils.getScaledValueY(LPUtils.TITLE_HEIGHT-5));
		mPageTab.setLayoutParams(lp);

		final View bottom = LayoutInflater.from(bv).inflate(R.layout.layout_home_bottom_view, null);
		int height = LPUtils.screenheight - Utils.getScaledValueY(LPUtils.TITLE_HEIGHT);
		LinearLayout.LayoutParams lpb = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, height);
		bottom.setLayoutParams(lpb);
		
		//九宫格存放视图
		mScrollView = (PageScrollView)bottom.findViewById(R.id.pagescroll);
		
		mPageTabBottom = (LinearLayout) bottom.findViewById(R.id.pagetabBottom);
		mPageTabBottom.setLayoutParams(lp);
		mPageTabBottom.setVisibility(View.GONE);
		
		int centerHeight_ = mTopView.getTopViewHeight() + Utils.getScaledValueY(LPUtils.TITLE_HEIGHT-5);
		
		verticalMenu.getCenterHeight(centerHeight_);
		verticalMenu.addScrollView();
		verticalMenu.addViews(center, bottom);
		
		titleNormal = (View)root.findViewById(R.id.normal);
		titleManage = (View)root.findViewById(R.id.edit);

		
		cancelButton = (Button)root.findViewById(R.id.cancelManage);
		confirmButton = (Button)root.findViewById(R.id.confirmManage);
		
		//标题栏左侧和右侧按钮
		titleLeft = (Button) root.findViewById(R.id.titleLeft);
		titleRight = (Button) root.findViewById(R.id.titleRight);
		
		//设置title高度 和标题栏左右侧按钮
		LPUtils.scaledTHeight((LinearLayout)titleNormal.getParent());
		LPUtils.setTitleButtonWH(cancelButton);
		LPUtils.setTitleButtonWH(confirmButton);
		LPUtils.setTitleButtonWH(titleLeft);
		LPUtils.setTitleButtonWH(titleRight);
		
		//设置开关按钮
		ivOpenClose = (ImageView)  root.findViewById(R.id.iconOpen);
		RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) ivOpenClose.getLayoutParams();
		rlp.topMargin = Utils.getScaledValueY(LPUtils.TITLE_HEIGHT)+rlp.topMargin;
		ivOpenClose.setLayoutParams(rlp);
		ivOpenClose.setImageResource(R.drawable.main_up);
		ivOpenClose.setVisibility(View.VISIBLE);
		ivOpenClose.setOnClickListener(this);
		
		//bottomLeft = (ImageView) root.findViewById(R.id.bottomLeft);
		bottomRight = (ImageView) root.findViewById(R.id.bottomRight);
		bottomRLayout = (RelativeLayout)root.findViewById(R.id.bottomRLayout);
		
		mCityView = (TextView) root.findViewById(R.id.citySelect);
		mCityImage = (ImageView)root.findViewById(R.id.imageSelect);
		
		setTitle();
		this.addView(root);
		
		verticalMenu.setMenuListener(new VerticalSlidingMenu.OnMenuListener() {
			
			@Override
			public void openMenu(boolean isOpen) {
				Message msg = new Message();
				msg.obj = isOpen;
				handler.sendMessage(msg);
			}
		});
	}
	
	public static Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			Object obj = msg.obj;
			if (obj instanceof Boolean) {
				if ((Boolean)obj) {
					bottomRLayout.setPadding(0, 0, 0, 0);
					bottomRLayout.setVisibility(View.VISIBLE);
					mPageTabBottom.setVisibility(View.GONE);
					ivOpenClose.setImageResource(R.drawable.main_up);
				} else {
					this.postDelayed(new Runnable() {
						
						@Override
						public void run() {
							bottomRLayout.setVisibility(View.GONE);
							mPageTabBottom.setVisibility(View.VISIBLE);
							ivOpenClose.setImageResource(R.drawable.main_down);
						}
					}, 500);
				}
			}
		}
	};

	/**
	 * 登陆成功后，将右上角的按钮替换为退出
	 */
	public void changeExit(){
		titleRight.setBackgroundResource(R.drawable.home_button_selector);
		titleRight.setText("退出");
	}
	
	/**
	 * 设置标题
	 */
	public void setTitle(){
		String version = LPMid.getInstance().read("version");
		if(null != version && version.equalsIgnoreCase("university")){
			String saveUniversity = LPMid.getInstance().read("university_select");
			if(null != saveUniversity && !"".equalsIgnoreCase(saveUniversity)){
				String[] university =  saveUniversity.split("\\|");
				mCityView.setText(university[0]);
			}else{
				mCityView.setText(R.string.push_message_title);
			}
		}else{
			String saveCity = PackageManagerAndroid.ANDROIDDB.get("city_select");
			if(null != saveCity && !"".equalsIgnoreCase(saveCity)){
				String[] city =  saveCity.split("\\|");
				mCityView.setText(city[1]);
			}else{
				mCityView.setText(R.string.push_message_title);
			}
		}
		//显示未读的消息
		//unreadnewscout = mData.unreadnewscount ;
		//if(unreadnewscout != null && !unreadnewscout.equalsIgnoreCase("") && !unreadnewscout.equalsIgnoreCase("0")){
		//	titleLeftnews.setText(unreadnewscout);
		//	titleLeftnews.setVisibility(View.VISIBLE);
		//}
	}
	/**
	 * 生成GridView和Tab里面的View
	 * */
	private void createView() {
		// TODO Auto-generated method stub
		tempList = new ArrayList<Map<String,Object>>(mData.array1);
		if (null != mData.mTitles) {
			int length = mData.mTitles.length;
			mDropGrids = new DropDragGrid[length];
			for (int i = 0; i < length; i++) {
				// 生成Tab
				TextView tab = (TextView) LayoutInflater.from(bv).inflate(R.layout.layout_home_tab, null);
				TextView tab1 = (TextView) LayoutInflater.from(bv).inflate(R.layout.layout_home_tab, null);
				tab.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.MATCH_PARENT, 1));
				tab1.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.MATCH_PARENT, 1));
				if(i == 0){
					tab.setBackgroundResource(R.drawable.menu_tab_left_sel);
					tab1.setBackgroundResource(R.drawable.menu_tab_left_sel);
				}else if(i == length-1){
					tab.setBackgroundResource(R.drawable.menu_tab_right_sel);
					tab1.setBackgroundResource(R.drawable.menu_tab_right_sel);
				}else{
					tab.setBackgroundResource(R.drawable.menu_tab_center_sel);
					tab1.setBackgroundResource(R.drawable.menu_tab_center_sel);
				}
				tab.setText(mData.mTitles[i]);
				tab1.setText(mData.mTitles[i]);
				mPageTab.addView(tab);
				mPageTabBottom.addView(tab1);

				final int index = i;
				tab.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if(DropGridAdapter.isInEdit){
							restoreMyFavorite();
							changeTitleView(false);							
						}
						changeTab(index);
						mScrollView.snapToScreen(index);
					}
				});
				tab1.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if(DropGridAdapter.isInEdit){
							restoreMyFavorite();
							changeTitleView(false);							
						}
						changeTab(index);
						mScrollView.snapToScreen(index);
					}
				});


				// 生成GridView
				mDropGrids[i] = new DropDragGrid(bv, true);
				mDropGrids[i].setOnScrollListener(new AutoScrollListener(callBack));
				ArrayList<Map<String, Object>> list = null;
				if (i == 0) {
					list = mData.array1;
				} else if (i == 1) {
					list = mData.array2;
				} else if (i == 2) {
					list = mData.array3;
				} else if (i == 3) {
					list = mData.array4;
				}

				if(i != 0){
					mDropGrids[i].setAdapter(new DropGridAdapter(bv,false, list));	
					mDropGrids[i].canDragParm = false;
				}else{
					favAdapter = new DropGridAdapter(bv,true, mData.array1);
					mDropGrids[i].setAdapter(favAdapter);
					mDropGrids[i].canDragParm = true;
				}
				mScrollView.addView(mDropGrids[i]);
				mDropGrids[i].setOnItemClickListener(new OnItemClickListener(){

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
						// TODO Auto-generated method stub
						doAction(index, position);
					}
				});
			}
		}
		//Utils.printOutToConsole(LPMid.getInstance().isTimeOut+"---"+LPMid.getInstance().currentTab);
		//当超时后，重建加密通道后切换到上次选择的频道
		if(mid.isTimeOut){
			changeTab(mid.currentTab);
			mScrollView.setToScreen(mid.currentTab);
		}else if(LPMid.isPushActivity){
			changeTab(LPMid.indexTab);
			mScrollView.setToScreen(LPMid.indexTab);
		}else{
			changeTab(0);
			mScrollView.setToScreen(0);
		}
		
		LPMid.isPushActivity = false;
		LPMid.indexTab = 0;
		
		//消息盒子未读数目显示
		//titleLeftnews = (TextView)root.findViewById(R.id.unreadnewsnum);
		new Handler().post(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				mSelectCity = new LPCitySelectView(bv,mCityView,BCMHomeView.this);
				mSelectCity.resetGroups();
				mSelectCity.resetView();
			}
		});
	}
	
	/**
	 * 回调方法
	 */
	private AutoLoadCallBack callBack = new AutoLoadCallBack() {
		
		@Override
		public void execute() {
			// TODO Auto-generated method stub
			//verticalMenu.showTopView();
		}
	};
	/**
	 * 点击九宫格后做的事件处理
	 * */
	protected void doAction(int current, int position) {
		// TODO Auto-generated method stub
		/**
		 * 加密通道未建完
		 */
		if(!LPToastUtil.isBuildChannel){
			((BOCMainHome)bv).showAlertDialog(true,null);
			return;
		}
		
		Map<String, Object> channel = null;
		LPToastUtil.getInstance().isBranchBank =false;
		
		switch (current) {
		case 0:// 第一个九宫格
			if (position == (mData.array1.size() - 1)) {
				if(!DropGridAdapter.isInEdit){
					if(LPMid.getInstance().um_.data.isLogin){
						manageHome = new LPManageHome(bv, this);
						manageHome.showWindow();					
					}else{
						((BOCMainHome)bv).showToast("不可操作，请登录后再做相应操作！");
					}					
				}
				return;
			}
			//当处于编辑状态时,除添加按钮，不响应点击
			if(titleManage.getVisibility() == View.VISIBLE ){
				return ;
			}
			channel = mData.array1.get(position);
			break;
		case 1:// 第二个九宫格
			channel = mData.array2.get(position);
			break;
		case 2:// 第三个九宫格
			channel = mData.array3.get(position);
			break;
		case 3:// 第四个九宫格
			channel = mData.array4.get(position);
			break;
		}

		final String id = (String) channel.get("id");
		// 如果id=最红商户，位置服务，周边搜索直接执行跳转方法
		if (id.equals("search_around")) {
			// 周边搜索
			mid.um_.jumpToLocationService(bv, id);
			return;
		}
		if (id.equals("red_shops")) {
			// 最红商户
			mid.um_.jumpToRedShop(bv,id);
			return;
		}
		if (id.equals("one_node_query")) {
			// 网点查询
			mid.um_.jumpToLocationService(bv, id);
			return;
		}
		
		/**
		 * 大智慧 UAT: big_Wisdom   sit:bigWisdom
		 */
		if (id.equalsIgnoreCase("big_Wisdom")) {
			dzhloadnotice();
			return;
		}
		
		String url = String.valueOf(channel.get("url"));
		//本地生活,判读是否是分行
		if (id.equals("native")) {
			LPToastUtil.getInstance().isBranchBank = true;
			mid.um_.jumpWithLocation(bv,locationServices,id,url,null);
			return;
		}
		
		//E代驾
		if(id.equalsIgnoreCase("traffic_e_drive")){
			gotoEDriveView(bv,id,url,String.valueOf(channel.get("name")));
			return;
		}
		
		//保存用户点击后的新图标
		String newChannel = (String) channel.get("user_id");
		if(null != newChannel && "new".equalsIgnoreCase(newChannel)){
			if(!mData.isSavedChannelId(id)){
				mData.saveClickedNewChannel(id);
				((DropGridAdapter)mDropGrids[current].getAdapter()).notifyDataSetChanged();
			}
		}
		
		LPMid.getInstance().um_.gotoEmpViewFromHome(bv, url,"");
	}
	
	/**
	 * 进入汽车代驾频道
	 * @param bv
	 */
	private void gotoEDriveView(final Activity bv,final String id,final String url,final String name){
		new AlertDialog.Builder(bv).setTitle("温馨提示").setMessage(R.string.e_drive)
		.setPositiveButton("取消", null)
		.setNegativeButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				mid.um_.jumpWithLocation((BaseViewCopy) bv,locationServices,id,url,name);
			}
		})
		.show();
	}
	
	/**
	 * 判断是否已经安装大智慧
	 */
	private  void dzhloadnotice(){
		Dialog dzhdig = new AlertDialog.Builder(bv)
		.setMessage(R.string.dzh_msg).setTitle("温馨提示")
		.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				if(!Utils.isInstalled(bv, "com.android.dazhihui")){
					mid.um_.copydzhapk(bv);
					mid.um_.installAPK( bv);
				}else{
					mid.um_.startDzhActivity(bv , "com.android.dazhihui");
				}
			}
		}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
			}
		}).create();
		dzhdig.show();
	}
	
	/**
	 * 改变标题栏View，是否显示编辑状态
	 * */
	public static void changeTitleView(boolean isEdit){
		if(isEdit){
			if(titleManage.getVisibility() == View.VISIBLE){
				return ;
			}
			mScrollView.setEnableScroll(false);
			titleNormal.startAnimation(topToBottom);
			titleManage.startAnimation(bottomToTop);
            
			titleNormal.setVisibility(View.GONE);
			titleManage.setVisibility(View.VISIBLE);
		}else{
			mScrollView.setEnableScroll(true);
			titleManage.startAnimation(topToBottom);
			titleNormal.startAnimation(bottomToTop);
			
			titleNormal.setVisibility(View.VISIBLE);
			titleManage.setVisibility(View.GONE);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.citySelect://城市里列表
			mSelectCity.showWindow();
			break;
		case R.id.imageSelect:
			mSelectCity.showWindow();
			break;
		case R.id.titleLeft://标题栏左侧按钮
			/*if(firstHitNewB == true){
				newsBoxShow();
				firstHitNewB = false ;
			}else{
				Intent intent = new Intent(bv,BCMNewsCenter.class);
				bv.startActivity(intent);
				titleLeftnews.setVisibility(View.GONE);
			}*/
			((BOCMainHome)bv).mSlideMenu.showLeftView();
			break;
		case R.id.titleRight://标题栏右侧按钮
			if(!mData.isLogin){
				((BOCMainHome)bv).mSlideMenu.showRightView();				
			}else{
				((BOCMainHome)bv).showLoginMessage();
			}
			break;
		case R.id.cancelManage://取消按钮
			restoreMyFavorite();
			changeTitleView(false);
			break;
		case R.id.confirmManage://完成按钮
			uploadToServer(false);
			break;
		//case R.id.bottomLeft://设置按钮
		//	((BOCMainHome)bv).mSlideMenu.showLeftView();
		//	break;
		case R.id.bottomRight://语音按钮
			if(!LPToastUtil.isBuildChannel){
				((BOCMainHome)bv).showAlertDialog(true,null);
				return;
			}
			((BOCMainHome)bv).JumpBankcommVoice();
			break;
		case R.id.iconOpen://显示隐藏广告栏按钮
			if (!isFastDoubleClick()) {
				verticalMenu.showTopView();
			}
		}
	}
	
	protected static long lastClickTime;
	
	/** 防止在短时间重复点击 **/
	public static boolean isFastDoubleClick() {
		long time = System.currentTimeMillis();
		long timeD = time - lastClickTime;
		if (0 < timeD && timeD < 800) {
			return true;
		}
		lastClickTime = time;
		return false;
	}
	
	/**
	 *请求消息盒子
	 */
	public void newsBoxShow(){
			WaitDialog waitdg = new WaitDialog();
			waitdg.addFgTask(bv, null, 0, 0, 0, new WaitDialog.Task(0) {
				String new_box_reply = "" ;
				@Override
				public void run(WaitDialog dlg) throws Exception {
					// TODO Auto-generated method stub
					String url = ConfigManager.NEWS_BOX ;
					String body = null ;
					new_box_reply = LPMid.getInstance().hm_.sendPostRequest(url, body, null, null, null).toString();
					new_box_reply = (AESCipher.decrypt(new_box_reply, AESCipher.serverKey_, AESCipher.serverIv_)).trim() ;
					Utils.printOutToConsole("xiaoxireply------------------->"+new_box_reply);
//					new_box_reply = Utils.getStringFormAsset(bv, "test.txt");
					mData.parsNewsReply(new_box_reply);
				}
				@Override
				public void onSuccess(WaitDialog dlg) {
					// TODO Auto-generated method stub
					super.onSuccess(dlg);
					bv.runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							Intent intent = new Intent(bv,BCMNewsCenter.class);
							bv.startActivity(intent);
							//titleLeftnews.setVisibility(View.GONE);//点击消息盒子，则取消首页未读消息显示
						}
					});
				}
				@Override
				public void onFailure(WaitDialog dlg) {
					// TODO Auto-generated method stub
					super.onFailure(dlg);
					bv.handleException(getErrMsg());
				}
				
			});
	}
	/**
	 * 显示城市框
	 * @param pop
	 */
	public static void showWindow(PopupWindow pop){
		if(null != pop && !pop.isShowing()){
			pop.showAsDropDown(titleNormal);
			mCityImage.setVisibility(View.INVISIBLE);
		}
	}
	
	/**
	 * 关闭城市框
	 */
	public static void dismissWindow(){
		mCityImage.setVisibility(View.VISIBLE);
	}

	/**
	 * 还原我的首页数据
	 */
	public void restoreMyFavorite(){
		mData.array1.clear();
		mData.array1.addAll(tempList);
		if(null != favAdapter){			
			favAdapter.stepIntoEditMode(false);
		}
	}
	
	/**
	 * 重置我的首页数据
	 */
	public void resetMyFavorite(){
		tempList.clear();
		tempList.addAll(mData.array1);
		if(null != favAdapter){
			favAdapter.notifyDataSetChanged();
		}
	}
	/**
	 * 添加到我的首页
	 * @param list
	 * */
	public void updateMyFavorite(ArrayList<Map<String,Object>> list){
		mData.array1.clear();
		mData.array1.addAll(list);
	}
	
	/**
	 *  将首页九宫格数据同步到服务器
	 * @param isAdd
	 */
	public void uploadToServer(final boolean isAdd){
		LPMid.getInstance().waitDialog_.addFgTask(bv, null, 0, 0, 0, new WaitDialog.Task(0) {
			Object result = null;
			@Override
			public void run(WaitDialog dlg) throws Exception {
				String url = mData.uploadURL;
				if(null != url && url.startsWith("/")){
					url = ConfigManager.SERVER_URI+url;
				}
				int limit = -1;
				if(null != mData.recommendList && mData.recommendList.size() > 0){
					limit = mData.recommendList.size();
				}
				
				String body = "";
				for (int i = 0; i < mData.array1.size(); i++) {
					if((limit > 0 && i < limit) || i == mData.array1.size()-1){
						continue;
					}
					Map<String,Object> item = mData.array1.get(i);
					String shortCut = item.get("id").toString();
					body = body+shortCut+"|";
				}
				
				if(null != body){
					if(body.endsWith("|")){
						body = body.substring(0, body.length()-1);
					}
					body = "menus="+body;
					Utils.printOutToConsole("body1-->"+body);
					body = AESCipher.encrypt(body, AESCipher.clientKey_, AESCipher.clientIv_);	
					Utils.printOutToConsole("body-->"+body);
				}

				result = LPMid.getInstance().hm_.sendPostRequest(url, body, this, null, null);

				//对报文做解密处理
				if(null != result && !"".equalsIgnoreCase(String.valueOf(result))){
					result = AESCipher.decrypt(String.valueOf(result), AESCipher.serverKey_, AESCipher.serverIv_);						
				}
				Utils.printOutToConsole("result-->"+result);
			}

			@Override
			public void onSuccess(WaitDialog dlg) {
				// TODO Auto-generated method stub
				if(null != result && result.equals("ok")){
					mData.saveToLocal(mData.array1);
					tempList.clear();
					tempList.addAll(mData.array1);
					bv.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							if(!isAdd){
								changeTitleView(false);								
							}
							if(null != favAdapter){
								favAdapter.stepIntoEditMode(false);								
							}
							if(null != manageHome){
								manageHome.closeWindow();
								manageHome = null;
							}
							String msg = "";
							if(isAdd){
								msg = "添加应用成功！";
							}else{
								msg = "操作成功！";
							}
							LPToastUtil.getInstance().getToast(msg, bv);
						}
					});
				}
				super.onSuccess(dlg);
			}

			@Override
			public void onFailure(WaitDialog dlg) {
				// TODO Auto-generated method stub
				super.onFailure(dlg);
				bv.handleException(getErrMsg());
			}
		});
	}
	
	/**
	 * 释放资源
	 */
	public void releaseResources(){
		mTopView.releaseResources();

		mDropGrids = null;
		if(null != tempList){
			tempList.clear();
			tempList = null;
		}
		Utils.releaseObject(titleRight);
		Utils.releaseObject(titleLeft);
		//Utils.releaseObject(bottomLeft);
		Utils.releaseObject(bottomRight);
		Utils.releaseObject(mCityImage);
	}
}
